package com.tangkeyon.controller.current;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.tangkeyon.common.Const;
import com.tangkeyon.common.ResponseCode;
import com.tangkeyon.pojo.User;
import com.tangkeyon.service.IOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author: tangkeyon@gmail.com
 * @Date: 2019/6/14 19:17
 * @Version 1.0
 */
@Controller
@RequestMapping("/order/")
public class OrderController {
    private static final Logger logger= LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private IOrderService iOrderService;

    @RequestMapping("create.do")
    @ResponseBody
    public Object create(HttpSession session,Integer shippingId){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return  ResponseCode.createByErrorMessage("请先登录");
        }
        return iOrderService.create(user.getId(),shippingId);
    }


    @RequestMapping("cancel.do")
    @ResponseBody
    public ResponseCode cancel(HttpSession session,Long orderNo){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return  ResponseCode.createByErrorMessage("请先登录");
        }
        return iOrderService.cancel(user.getId(),orderNo);
    }

    @RequestMapping("get_order_cart_product.do")
    @ResponseBody
    public ResponseCode getOrderCartProduct(HttpSession session){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return  ResponseCode.createByErrorMessage("请先登录");
        }
        return iOrderService.getOrderCartProduct(user.getId());
    }

    @RequestMapping("detail.do")
    @ResponseBody
    private ResponseCode detail(HttpSession session,Long orderId){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return  ResponseCode.createByErrorMessage("请先登录");
        }
        return iOrderService.detail(user.getId(),orderId);
    }

    private ResponseCode list(HttpSession session,
                              @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "0") Integer pageNum){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return  ResponseCode.createByErrorMessage("请先登录");
        }
        return iOrderService.list(user.getId(),pageSize,pageNum);
    }

    /**
     * @Description: 支付订单
     * @param session
     * @param request
     * @param orderId
     * @return
     */
    @RequestMapping("pay.do")
    @ResponseBody
    public ResponseCode pay(HttpSession session, HttpServletRequest request,Long orderId){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return  ResponseCode.createByErrorMessage("请先登录");
        }
        String path = request.getSession().getServletContext().getRealPath("upload");
        return iOrderService.pay(user.getId(),orderId,path);
    }

    /**
     * @Description: 该接口是让支付宝调用的,用户在扫码支付后,返回用户支付的相关信息为相关数据表赋值，并最终返回是否付款成功
     * @param request
     * @return
     */
    @RequestMapping("alipayCallBack.do")
    @ResponseBody
    public Object alipayCallBack(HttpServletRequest request){
       //获取回调的的各种参数，用map盛放
        Map<String,String> resultMap= Maps.newHashMap();
        String paramValue="";
        Map<String, String[]> paramsMap = request.getParameterMap();
        for(String temp:paramsMap.keySet()){
            String[] valueArr = paramsMap.get(temp);
            //下面的这种写法很值得学习
           for(int i=0;i<valueArr.length;i++){
            //如果数组中只有一个元素或者遍历到数组中的最后一个元素了就直接添加，若不是就添加一个数据再加一个,
               paramValue=(i==valueArr.length-1)? paramValue+valueArr[i]:paramValue+valueArr[i]+",";
           }
           resultMap.put(temp,paramValue);
        }
        logger.info("支付宝回调，sign:{},trade_status:{},参数:{}",resultMap.get("sign"),resultMap.get("trade_status"),resultMap.toString());
        // 验证回调的准确性，看是否来自支付宝的回调,用返回的支付宝公钥进行验证
        resultMap.remove("sign_type");
        try {
            boolean callBackSuccess = AlipaySignature.rsaCheckV2(resultMap, Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            if(!callBackSuccess){
                return  ResponseCode.createByErrorMessage("非法请求，验证不通过");
            }
          } catch (AlipayApiException e) {
              logger.error("支付宝验证回调异常",e);
        }
        //调用service确认支付宝是否存在重复通知，对各种与订单有关的参数校验，校验成功后将回调的参数保存到相关数据表中
        ResponseCode responseCode = iOrderService.alipayCallBack(resultMap);
        if(responseCode.ifSuccess()){
            return Const.AliPayCallBackStatus.RESPONSE_SUCCESS;
        }
        return Const.AliPayCallBackStatus.RESPONSE_FAILED;
    }

    /**
     * @Description: 查询用户的订单状态
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("query_order_pay_info")
    @ResponseBody
    public ResponseCode<Boolean> queryOrderPayInfo(HttpSession session,Long orderNo){
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(user==null){
            return ResponseCode.createByErrorMessage("请先登录");
        }
        ResponseCode<Boolean> booleanResponseCode = iOrderService.queryOrderStatus(user.getId(), orderNo);
        if(booleanResponseCode.ifSuccess()){
            return ResponseCode.creatBySuccess(true);
        }
        return ResponseCode.creatBySuccess(false);
    }
}
